import { create } from 'dva-core'
import createLoading from 'dva-loading'
import state from './state'
import { writeCache, readCache } from './dva-cache'
import temp from './models/temp'
import tabbar from './models/tabbar'

function createApp(opts: { initialState: any, models: any[] }) {
    
    let app = create(opts)
    app.use(createLoading({}))
    app.use({
      onStateChange: (state) => {
        writeCache(state)
      }
    })

    app.use({
      onReducer: (reducer) => {

        return (state, action) => {
          if (action.type == "session/logout") {
            return reducer(
              { 
                config: state.config, 
                temp: temp.state,
                tabbar: tabbar.state
              },
               action)
          }
          return reducer(state, action)
        }
      }
    })

    opts.models.forEach(model => app.model(model))
    app.start()
  
    let store = app._store
    app.getStore = () => store

    app.use({
      onError(err) {
        console.log(err)
      },
    })
  
    app.dispatch = store.dispatch
    return app
}


let app = createApp({ initialState: readCache() ?? state.initialState, models: state.models})

export default {
    app,
    getDispatch() {
        return app.dispatch
    }
}